<?php

/**
 * CelebrioMail MailServer
 *
 * @copyright  Copyright (c) 2011 Celebrio Software
 * @package    CelebrioMail
 */

namespace ApplicationsModule\TalkerModule;

use \Nette\Object;
use \Nette\Environment;

/**
 * TODO: cURL communication could become library
 *
 * @author Celebrio Software
 */
class ImoCommunicator extends Object {
    
    private $talker;
    
    public function __construct() {
        $this->talker = Environment::getSession()->getNamespace("talker");
        $this->talker->setExpiration(0);
    }

    private function curl($data) {
        //\Nette\Debug::dump($data);
        file_put_contents("C:\\tmp\\a.txt", date("H:i:s")." - cURL called". PHP_EOL, FILE_APPEND);
        if (!Environment::getUser()->isLoggedIn()) {
            throw new \Exception("User has to be logged in");
        }
        
        $user = Environment::getUser()->getIdentity()->name;
        //file_put_contents(Environment::getVariable("tempDir")."/$user.txt", $this->talker->cookie);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://imo.im/imo");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
        //curl_setopt($ch, CURLOPT_COOKIEJAR, Environment::getVariable("tempDir")."/$user.txt");
        //curl_setopt($ch, CURLOPT_COOKIEFILE, Environment::getVariable("tempDir")."/$user.txt");
        curl_setopt($ch, CURLOPT_COOKIEJAR, "C:\tmp\identity.txt");
        curl_setopt($ch, CURLOPT_COOKIEFILE, "C:\tmp\identity.txt");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 1);
        curl_setopt($ch, CURLOPT_REFERER, "https://imo.im");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HEADER, TRUE);

        $output = curl_exec($ch);
        file_put_contents("C:\\tmp\\a.txt", date("H:i:s")." - cURL executed". PHP_EOL, FILE_APPEND);
        if ($output === false) {
            $message = curl_error($ch);
            curl_close($ch);
        }
        $pos = strpos($output, "{");
        $return = substr($output, $pos);
        curl_close($ch);        
        //$this->talker->cookie = file_get_contents(Environment::getVariable("tempDir")."/$user.txt");
        file_put_contents("C:\\tmp\\a.txt", date("H:i:s")." - cURL exit". PHP_EOL, FILE_APPEND);
        return json_decode($return);
    }

    public function message($method, $json) {
        return $this->curl("method=$method&data=".urlencode($json));
    }
}